<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑/添加</title>
</head>
<body>
    <table>
        <tr>
            <td><label for="">商品名称：</label></td>
            <td><input type="text" placeholder="请输入商品名称" name="productName"></td>
        </tr>
        <tr>
            <td><label for="">售价：</label></td>
            <td><input type="text" placeholder="请输入价格" name="price"></td>
        </tr>
        <tr>
            <td><label for="">库存：</label></td>
            <td><input type="text" placeholder="请输入库存数量" name="stockNum"></td>
        </tr>
        <tr>
            <td><label for="">供应商：</label></td>
            <td><input type="text" placeholder="请输入供应商" name="supplire"></td>
        </tr>
        <tr>
            <td><input type="button" value="保存" onclick="save()"></td>
            <td><input type="button" value="取消并返回" onclick="cancel()"></td>
        </tr>
        <script src="./js/jquery-3.6.0.min.js"></script>
        <script src="./js/api.js"></script>
        <script>
            $(function(){
                let id=getUrlParam('id');
                getProductById(id).then(res=>{
                    console.log(res);
                    let obj=res.data;
                    $('[name=productName]').val(obj.productName);
                    $('[name=price]').val(obj.price);
                    $('[name=stockNum]').val(obj.stockNum);
                    $('[name=supplire]').val(obj.supplire);
                })
            })

            
            function getUrlParam(name) {
                var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)"); 
                var r=window.location.search.substr(1).match(reg); 
                if (r != null) return unescape(r[2]); return null; 
            }


            function save(){
                let id=getUrlParam('id');
                let obj={
                    productName: $('[name=productName]').val(),
                    price: $('[name=price]').val(),
                    stockNum: $('[name=stockNum]').val(),
                    supplire: $('[name=supplire]').val(),
                }
                if(id){
                    updateProduct(id, obj).then(res=>{
                        location.href='./index.html';
                    })
                }else{
                    let params={
                        productName:obj.productName,
                        price:obj.price,
                        stockNum:obj.stockNum,
                        supplire:obj.supplire
                    }
                    addProduct(params).then(res=>{
                        location.href='./index.html';
                    })
                }
            }


            function cancel(){
                location.href='./index.html';
            }
        </script>
    </table>
</body>
</html>